package com.finance.system.controller;

import com.finance.base.constant.BaseConstants;
import com.finance.base.exception.BaseException;
import com.finance.framework.controller.BaseController;
import com.finance.framework.controller.Result;
import com.finance.framework.lang.BeanUtils;
import com.finance.framework.lang.Page;
import com.finance.framework.lang.PageResultBO;
import com.finance.system.bean.pojo.*;
import com.finance.system.request.LogisticsListReq;
import com.finance.system.request.LogisticsReq;
import com.finance.system.service.ILogisticsManageService;
import com.finance.util.DateUtil;
import com.mysql.jdbc.MysqlErrorNumbers;
import org.apache.commons.lang.StringUtils;
import org.springframework.jdbc.BadSqlGrammarException;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.text.ParseException;
import java.util.Date;


/**
 * @Author: gly
 * @Date: Created in 2017-05-18
 */
@Controller
@RequestMapping("/system/logistics")
public class LogisticsManagerController extends BaseController {

    @Resource
    private ILogisticsManageService logisticsManageService;

    @RequestMapping("/index")
    public String index() {
        return "system/logistics/index";
    }

    @RequestMapping("/list")
    public Result list(LogisticsListReq form) {
        try {
            if( StringUtils.isNotBlank(form.getStartTime()) && StringUtils.isBlank(form.getEndTime()) ){
                return getFailResult(BaseConstants.ERR_TIME,"结束时间不能为空");
            }
            if( StringUtils.isNotBlank(form.getEndTime()) && StringUtils.isBlank(form.getStartTime()) ){
                return getFailResult(BaseConstants.ERR_TIME,"开始时间不能为空");
            }
            if( StringUtils.isNotBlank(form.getStartTime()) && StringUtils.isNotBlank(form.getEndTime()) ){
                if( DateUtil.compare_date( DateUtil.str2date(form.getStartTime() + " 00:00:00") , DateUtil.str2date(form.getEndTime() + " 23:59:59") ) == 1){
                    return getFailResult(BaseConstants.ERR_TIME,"开始时间不能大于结束时间");
                }
            }
        } catch (ParseException e) {
            e.printStackTrace();
        }

        Page page = Page.getInstance(form);
        LogisticsList logisticsList = new LogisticsList();
        logisticsList.setBusinessCode(form.getBusinessCode());
        logisticsList.setWaybillNum(form.getWaybillNum());
        logisticsList.setDirection(form.getDirection());
        logisticsList.setMobileConsignee(form.getMobileConsignee());
        logisticsList.setNameConsignee(form.getNameConsignee());
        logisticsList.setOrgnameDelivery(form.getOrgnameDelivery());
        logisticsList.setPostmanName(form.getPostmanName());
        logisticsList.setPostmanNo(form.getPostmanNo());
        logisticsList.setMonth(form.getMonth());
        if( StringUtils.isNotBlank(form.getStartTime()) && StringUtils.isNotBlank(form.getEndTime()) ){
            logisticsList.setStartTime(form.getStartTime() + " 00:00:00");
            logisticsList.setEndTime(form.getEndTime() + " 23:59:59");
        }
        String tableName =BaseConstants.SYSCONFIG_KEY_LOGISTICDATA_TABLE + form.getMonth().replace("-","").substring(2,6);
        logisticsList.setTableName(tableName);
        page.setParams(logisticsList);
        PageResultBO<Logistics> pageResultBO = logisticsManageService.listByPage(page);
        return getSuccessResult(pageResultBO);

    }

    @RequestMapping(value = "/update", method = RequestMethod.GET)
    public String update(String id, String signTime, HttpServletRequest httpServletRequest) {
        String tableName = "";
        tableName = BaseConstants.SYSCONFIG_KEY_LOGISTICDATA_TABLE + DateUtil.long2Str(Long.parseLong(signTime), "yyMM");
        Logistics logistics = null;
        try {
            logistics = logisticsManageService.getById(Long.parseLong(id), tableName);
        }catch (BadSqlGrammarException e){
            int errCode=e.getSQLException().getErrorCode();
            if(errCode== MysqlErrorNumbers.ER_NO_SUCH_TABLE){
                throw new BaseException(BaseConstants.ERR_TABLE_NAME_NOT_EXIST);
            }
        }
        httpServletRequest.setAttribute("logistics", logistics);
        return "system/logistics/update";
    }

    @RequestMapping(value = "/update", method = RequestMethod.POST)
    public Result update(String id, String signTime, @Valid LogisticsReq logisticsReq) {
        String tableName = "";
        try {
            tableName = BaseConstants.SYSCONFIG_KEY_LOGISTICDATA_TABLE + DateUtil.dateFormat(DateUtil.str2date(signTime), "yyMM");
        } catch (ParseException e) {
            logger.error(e.getMessage(),e);
        }
        if (StringUtils.isBlank(id)) {
            throw new BaseException(BaseConstants.ERR_INVALID_PARAMETER);
        }
        Logistics oldLogistics = logisticsManageService.getById(Long.valueOf(id), tableName);
        if (oldLogistics == null) {
            throw new BaseException(BaseConstants.ERR_NON_EXISTENT);
        }
        User user = getAuthUser();
        if (user == null) {
            throw new BaseException(BaseConstants.ERR_UNKONW_USER);
        }
        Logistics logistics = convertBeanFromFrom(logisticsReq);
        logistics.setUpdateUid(user.getId());
        logistics.setId(Long.valueOf(id));
        try {
            logisticsManageService.update(logistics, tableName);
        }catch (BadSqlGrammarException e){
            int errCode=e.getSQLException().getErrorCode();
            if(errCode== MysqlErrorNumbers.ER_NO_SUCH_TABLE){
                throw new BaseException(BaseConstants.ERR_TABLE_NAME_NOT_EXIST);
            }
        }
        return getSuccessResult("修改运单信息成功");

    }

    private Logistics convertBeanFromFrom(LogisticsReq logisticsReq) {
        Logistics logistics = new Logistics();
        Supplier supplier = new Supplier();
        supplier.setCode(logisticsReq.getSupplierCode());
        logistics.setSupplier(supplier);
        Organization acceptOrganzation = new Organization();
        acceptOrganzation.setOrgCode(logisticsReq.getOrgcodeAccept());
        Organization currentOrganzation = new Organization();
        currentOrganzation.setOrgCode(logisticsReq.getOrgcodeCurrent());
        Organization deliveryOrganzation = new Organization();
        deliveryOrganzation.setOrgCode(logisticsReq.getOrgcodeDelivery());
        Organization targetOrganzation = new Organization();
        targetOrganzation.setOrgCode(logisticsReq.getOrgcodeTarget());
        logistics.setOrgAccept(acceptOrganzation);
        logistics.setOrgCurrent(currentOrganzation);
        logistics.setOrgDelivery(deliveryOrganzation);
        logistics.setOrgTarget(targetOrganzation);
        try {
            BeanUtils.copyProperties(logistics, logisticsReq);
        } catch (Exception e) {
            throw new BaseException(BaseConstants.ERR_COPYBEAN);
        }
        return logistics;
    }

    @RequestMapping(value = "/detail.htm",method = RequestMethod.GET)
    public String detail(String id, String signTime, HttpServletRequest request){
        String dataTableName = BaseConstants.SYSCONFIG_KEY_LOGISTICDATA_TABLE + DateUtil.long2Str(Long.parseLong(signTime), "yyMM");
        String extendTableName = BaseConstants.SYSCONFIG_KEY_LOGISTICS_EXTEND_TABLE + DateUtil.long2Str(Long.parseLong(signTime), "yyMM");
        Logistics logistics = logisticsManageService.getDetailById(dataTableName,extendTableName,Long.parseLong(id));
        request.setAttribute("logistics",logistics);
        return "system/logistics/detail";
    }
}
